package main

import (
	"encoding/json"
	"fmt"
	tea "github.com/charmbracelet/bubbletea"
	etable "github.com/evertras/bubble-table/table"
	_ "github.com/go-sql-driver/mysql"
	"os"
	"reflect"
	database "tui-sql/db"
	"tui-sql/views"
)

type Log struct {
	id int64 `db:"id"`
}

func main() {
	// connect mysql server
	db := database.InitDb()
	// 解析row
	//log := Log{}
	rows, err := db.Queryx("SELECT * FROM cloud_streams;")
	if err != nil {
		panic(err)
	}
	var data []map[string]interface{}
	var colKeys []string
	for rows.Next() {
		a := map[string]interface{}{}
		colKeys, err = database.MapScanWithSortedKeys(rows, a)
		if err != nil {
		}
		data = append(data, a)
	}

	var rows2 []etable.Row
	var cols []etable.Column
	for _, v := range colKeys {
		cols = append(cols, etable.NewColumn(v, v, len(v)))
		//cols = append(cols, etable.NewColumn(v, v, 10))
	}

	for _, v := range data {
		for _, colKey := range colKeys {
			val, exists := v[colKey]
			if !exists || val == nil {
				v[colKey] = nil
				continue
			}
			if bytes, ok := val.([]uint8); ok {
				var jsonObj interface{}
				err := json.Unmarshal(bytes, &jsonObj)
				if err != nil {
					v[colKey] = string(bytes)
					//panic(err)
				} else {
					v[colKey] = jsonObj
				}
			} else if v3, ok := val.(string); ok {
				v[colKey] = v3
			} else if v4, ok := val.(float32); ok {
				//v[colKey] = fmt.Sprintf("%f", v4)
				v[colKey] = v4
			} else if v5, ok := val.(int64); ok {
				//v[colKey] = fmt.Sprintf("%d", v5)
				v[colKey] = v5
			} else {
				of := reflect.TypeOf(val)
				fmt.Println(of)
			}
		}
		var row = etable.NewRow(v)
		rows2 = append(rows2, row)
	}

	newModel := views.NewModel()
	newModel.Cols = cols
	newModel.Rows = rows2
	if _, err := tea.NewProgram(newModel).Run(); err != nil {
		fmt.Println("Error running program:", err)
		os.Exit(1)
	}

}
